package com.yl.projects.ui

import androidx.fragment.app.Fragment
import com.google.android.material.tabs.TabLayoutMediator
import com.yl.common.base.BaseVMFragment
import com.yl.common.network.BaseResp
import com.yl.common.network.BaseStateObserver
import com.yl.projects.R
import com.yl.projects.adapter.ProjectAdapter
import com.yl.projects.bean.ProjectType
import com.yl.projects.databinding.FragmentProjectBinding
import com.yl.projects.viewmodel.ProjectViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel

class ProjectsFragment : BaseVMFragment<FragmentProjectBinding>() {

    private val projectViewModel: ProjectViewModel by viewModel()

    private var titleList = ArrayList<String>()
    private var fragmentList = ArrayList<Fragment>()
    private lateinit var projectAdapter: ProjectAdapter

    override fun getLayoutID() = R.layout.fragment_project


    override fun observe() {
        projectViewModel.projectList.observe(this,
            object : BaseStateObserver<List<ProjectType>>(null) {
                override fun getRespDataSuccess(it: BaseResp<List<ProjectType>>) {
                    initTab(it.data!!)
                }
            })
    }

    override fun init() {
        projectViewModel.getProTypeList()

    }

    private fun initTab(list: List<ProjectType>) {
        for (i in list.indices) {
            titleList.add(list[i].name)
            fragmentList.add(ProjectChildFragment.newInstance(list[i].id, i))
        }
        projectAdapter = ProjectAdapter(this, fragmentList)
        mBind.viewPager.adapter = projectAdapter
        mBind.viewPager.offscreenPageLimit = 5
        mBind.viewPager.isSaveEnabled = false
        TabLayoutMediator(mBind.tabLayout, mBind.viewPager) { tab, position ->
            tab.text = titleList[position]
        }.attach()
    }

//    fun scrollToTop() {
//        if (projectAdapter.getItemCount() == 0) {
//            return
//        }
//        val fragment: ProjectChildFragment = projectAdapter.createFragment(mBind.viewPager.currentItem) as ProjectChildFragment
//        fragment.scrollToTop()
//    }
}